package com.viknix.threadpool.manager.client.core;

import com.viknix.threadpool.manager.client.listener.Listener;

import java.util.concurrent.Executor;

/**
 * @Author: Dongqi
 * @Date: 2021/10/21 13:32
 * @Version 1.0
 * @Description ThreadPoolOperation
 */
public class ThreadPoolOperation {

    /**
     * 客户端命名空间
     */
    private String namespace;

    /**
     * 客户端项目编号
     */
    private String projectId;

    private final ConfigService configService;

    public ThreadPoolOperation(String namespace, String projectId, ConfigService configService) {
        this.namespace = namespace;
        this.projectId = projectId;
        this.configService = configService;
    }

    /**
     * 订阅远端线程池配置：将 cacheData 绑定到 cacheMap，Listener 绑定到 cacheData
     *
     * @param threadPoolId                线程池id
     * @param executor                    执行动态刷新线程池参数工作的 work线程池
     * @param threadPoolSubscribeCallback 回调函数，动态刷新方法
     * @return 线程池监听器对象
     */
    public Listener subscribeConfig(String threadPoolId, Executor executor, ThreadPoolSubscribeCallback threadPoolSubscribeCallback) {

        // 构建该动态线程池的客户端监听器，用于在服务端配置发生更新时，动态刷新该线程池的配置
        Listener configListener = new Listener() {
            @Override
            public void receiveConfigInfo(String config) {
                threadPoolSubscribeCallback.callback(config);
            }

            @Override
            public Executor getExecutor() {
                return executor;
            }
        };
        // 将该线程池信息封装成为 ThreadPoolDatum 对象，并且将监听器存储到 ThreadPoolDatum 对象中
        configService.addListener(threadPoolId, projectId, configListener);
        return configListener;
    }

}
